package de.homelabs.modules.template.service;

import java.io.IOException;
import java.io.Reader;

import org.springframework.stereotype.Component;

import de.homelabs.modules.template.domain.HLTemplateElement;
import freemarker.cache.TemplateLoader;

/**
 * Wrapper to use HLTemplateManager als FreemarkerTemplateLoader
 * 
 * @author D.Mueller
 *
 */
@Component("hLTemplateManagerTemplateLoader")
public class HLTemplateManagerTemplateLoader implements TemplateLoader {

	/*
	 * (non-Javadoc)
	 * @see freemarker.cache.TemplateLoader#findTemplateSource(java.lang.String)
	 */
	public Object findTemplateSource(String name) throws IOException {
		return HLTemplateManager.getInstance().findTemplate(name);
	}

	/*
	 * (non-Javadoc)
	 * @see freemarker.cache.TemplateLoader#getLastModified(java.lang.Object)
	 */
	public long getLastModified(Object templateSource) {
		//we dont allow template change at runtime :-)
		//TODO: get last import date
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * @see freemarker.cache.TemplateLoader#getReader(java.lang.Object, java.lang.String)
	 */
	public Reader getReader(Object templateSource, String encoding)
			throws IOException {
		//we only support HLTemplateELement here
		if (templateSource instanceof HLTemplateElement){
			return HLTemplateManager.getInstance().getTemplateReader((HLTemplateElement) templateSource);
		} else
			return null;
	}

	/*
	 * (non-Javadoc)
	 * @see freemarker.cache.TemplateLoader#closeTemplateSource(java.lang.Object)
	 */
	public void closeTemplateSource(Object templateSource) throws IOException {
		if (templateSource instanceof HLTemplateElement){
			//TODO: irgendwie den Status abarbeiten?
			HLTemplateManager.getInstance().closeTemplateReader((HLTemplateElement) templateSource);
			return;
		}
	}

}
